package org.example.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.MessageRequestPacket;
import org.example.MessageResponsePacket;
import org.example.im.SessionUtil;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) {
        System.out.println("消息处理：收到的消息：消息格式：[用户id 接收方 消息内容]" + messageRequestPacket);
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());
        messageResponsePacket.setFromUserId(SessionUtil.getUserId(ctx.channel()));

        // 获取发给谁
        Channel targetChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());

        if(null != targetChannel && SessionUtil.hasLogin(targetChannel)){
            System.out.println("发送消息给用户结束.用户：" + messageRequestPacket.getToUserId());
            targetChannel.writeAndFlush(messageResponsePacket);
        }else {
            System.out.println(messageRequestPacket.getToUserId() + "不在线，发送失败。");
        }
    }
}
